package com.jxw.cloudpen.web.microsoft.stremspeed;

import com.alibaba.fastjson.JSONObject;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.framing.Framedata;
import org.java_websocket.framing.FramedataImpl1;
import org.java_websocket.handshake.ServerHandshake;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.sound.sampled.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

import static com.jxw.cloudpen.web.microsoft.stremspeed.WebSocketClientAI.clientId;

public class WebSocketClientBrenAI extends org.java_websocket.client.WebSocketClient {

    static Boolean isStop = false;
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    static Boolean isImgStop = true;
    static String token = "login_jxwdevice213837246ff8nqc4cbkhqqr7rh3l6e5yapep4w80";
    static long startTime = System.currentTimeMillis();

    static Boolean isBrek = false;
    static int ttsNum = 0;

//    static String txt = "今天天气怎么样";

    static String txt = "九九乘法表";

    public WebSocketClientBrenAI(URI serverUri) {
        super(serverUri);
    }

    public WebSocketClientBrenAI(URI serverUri, Draft protocolDraft, Map<String, String> httpHeaders, int connectTimeout) {
        super(serverUri, protocolDraft, httpHeaders, connectTimeout);
    }

    /**
     * 启动定时发送ping的定时器
     */

    private Timer pingTimer;

//    @Override
//    public void onWebsocketPong(WebSocket conn, Framedata f) {
        public void onWebsocketPong() {

        if (pingTimer != null) {
            pingTimer.cancel();
        }
        pingTimer = new Timer("WebSocket-Ping-Timer", true);
        // 定时发送ping，延迟0秒开始，每PING_INTERVAL秒执行一次
        pingTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (isOpen()) { // 连接打开状态才发送ping
                    // 当ping生效后，会返回一个Pong信息，这里接收到Pong后等待一秒后再发送一个ping
//                    System.out.println("接收到ping返回的pong回复");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ByteBuffer pingData = ByteBuffer.wrap(("PING").getBytes());
                    FramedataImpl1 framedataImpl1 = FramedataImpl1.get(Framedata.Opcode.TEXT);
                    framedataImpl1.setPayload(pingData);
                    sendFrame(framedataImpl1);
                    // 发送ping后，检查是否在超时时间内收到pong
                }
            }
        }, 0, 1 * 1000L);



//        // 当ping生效后，会返回一个Pong信息，这里接收到Pong后等待一秒后再发送一个ping
//        System.out.println("接收到ping返回的pong回复");
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        ByteBuffer pingData = ByteBuffer.wrap(("ping-" + System.currentTimeMillis()).getBytes());
//        FramedataImpl1 framedataImpl1 = FramedataImpl1.get(Framedata.Opcode.TEXT);
//        framedataImpl1.setPayload(pingData);
//        this.sendFrame(framedataImpl1);
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        System.out.println("Connected");
//        onWebsocketPong();
//        this.send("Hello Server!"); // 发送消息到服务器
//        for(;;){
//            this.send(ByteObjUtil.objToBytes("aaaa"));
//            this.send("aaaa");
//            try {
//                Thread.sleep(3000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
        try {
            executeTxt();
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        }
//        while(true){
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            this.send(JSONObject.toJSONString(request));
//        }
//        try {
//            executeMusic();
//        } catch (LineUnavailableException e) {
//
//        }

    }


    private static TargetDataLine targetDataLine;

    private static volatile BlockingQueue<byte[]> sharedQueue = new LinkedBlockingQueue<byte[]>();
    static Long time = System.currentTimeMillis();


    public StreamData executeTxt() throws LineUnavailableException {
        AiSocketChatDTO result = new AiSocketChatDTO();
        result.setTxt(txt);
        this.send(JSONObject.toJSONString(result));
        System.out.println(String.format("data : %s  send succ time: %s", simpleDateFormat.format(new Date()),txt));
        return null;
    }


    static Long message_pre_l =0L;
    static Long tts_pre_l =0L;
    static boolean pan = true;
    static Long clientId = 0L;

    static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    @Override
    public void onMessage(String message) {
//        System.out.println(String.format("data : %s  Received: %s", simpleDateFormat.format(new Date()), message));

        JSONObject jsonObject = JSONObject.parseObject(message).getJSONObject("data");
        Long clientId2 = jsonObject.getLong("conversationId");

        String event = jsonObject.getString("event");
        if (event.indexOf("tts_") > -1) {
//            if ((++ttsNum) < 5) {
            JSONObject jsonObject1 =  JSONObject.parseObject(message);
                System.out.println(String.format("data : %s  Received: %s", simpleDateFormat.format(new Date()), jsonObject1.getJSONObject("data").getString("event")));
//            System.out.println(String.format("data : %s  Received: %s", simpleDateFormat.format(new Date()), message));
//            }
        } else {
            System.out.println(String.format("data : %s  Received: %s", simpleDateFormat.format(new Date()), message));
        }


        if("message_pre".equals(event)){
            message_pre_l = System.currentTimeMillis();
        }
        if("tts_message".equals(event) && tts_pre_l==0){
            tts_pre_l = System.currentTimeMillis();
        }
        if("tts_message_end".equals(event)){
            System.out.println(String.format("tts 第一帧耗时 : %s  ", (tts_pre_l - message_pre_l)));
        }
        if (pan && "start".equals(event)) {
            startTime = System.currentTimeMillis();
            clientId = clientId2;
            pan = false;
            executorService.submit(() -> {
                try {
                    executeTxt();
                } catch (LineUnavailableException e) {

                }
            });


        }

        //发送图片

    }


    @Override
    public void onMessage(ByteBuffer bytes) {
        System.out.println("Received22: " + bytes);
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("Disconnected");
    }

    @Override
    public void onError(Exception ex) {
        System.err.println("Error: " + ex.getMessage());
    }

    public static void main(String[] args) throws URISyntaxException, Exception, NoSuchAlgorithmException {
        startTime = System.currentTimeMillis();
//        String url = "ws://gwsdb-sgp-test.xuexizhiwang.com/stream-speech";

//        String url = "ws://gwpad.xuexizhiwang.com/stream-speech";
//        String url = "wss://gw-test.xuexizhiwang.com:443/test";

//        String url = "ws://gw-pre.xuexizhiwang.com/stream-speech";
//        String url = "ws://gw-pre.xuexizhiwang.com/stream-speech";
//        String url = "ws://172.26.28.68:6601/ai/dialogue/mood";
//        String url = "ws://localhost:6601/ai/dialogue/txtChat";
        String url = "wss://gw-test.xuexizhiwang.com/ai/dialogue/txtChat";
//        String url = "ws://172.26.28.68:6601/ai/stream/asr";
//        String url = "ws://gw-test.xue
//
//
//        xizhiwang.com/ai/stream/asr";
//        String url = "ws://gw-test.xuexizhiwang.com/ai/dialogue/txtChat";

//        http://172.19.192.29:9050
//        String url = "ws://gw-bench.xuexizhiwang.com/ai/dialogue/txtChat";


//        String url = "ws://gw-test.xuexizhiwang.com/ai/dialogue/mood";
//        String url = "ws://172.26.28.68:6601/stream-speech";

        Map<String, String> headers = new HashMap<>();
        headers.put("token", token);
        Draft draft = new Draft_6455();
        // 创建信任所有证书的SSL上下文（仅用于测试）
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[]{new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                // 信任所有客户端证书
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                // 信任所有服务器证书
            }
        }}, new java.security.SecureRandom());
//        String url = "ws://localhost:6601/websocket";
        WebSocketClientBrenAI client = new WebSocketClientBrenAI(new URI(url), draft, headers, 50000); // 替换为你的WebSocket服务器地址和端点
        client.setSocket(sslContext.getSocketFactory().createSocket());

        client.connect();
    }
}
